package part12;

/**
 * @author wcj
 * @Date 2021/5/21 15:35
 * @Version 1.0
 */
public class Part127 {

    public static void f() throws Exception {
        System.out.println("Exception from f()");
        throw new Exception("throw Exception from f()");
    }

    public static void g() throws Exception {
        try {
            f();
        } catch (Exception e) {
            System.out.println("Inside g(),e.printStackTrace()");
            e.printStackTrace(System.out);
            throw e;
        }
    }

    public static void h() throws Exception {
        try {
            f();
        } catch (Exception e) {
            System.out.println("Inside h(),e.printStackTrace()");
            e.printStackTrace(System.out);
            // e.fillInStackTrace()方法会使得当前异常抛出位置称为异常的发生地，而不是追溯到e的根源f方法处
            // 这个捕获异常之后抛出另一种异常是同样的道理，新的异常会成为异常发生地
            // Throwable 和其三个子类Error,Exception,RuntimeException都含有一个包含cause的构造器，可以打印完成的异常链
            throw (Exception) e.fillInStackTrace();
        }
    }

    public static void main(String[] args) {
        try {
            g();
        } catch (Exception e) {
            System.out.println("main:printStackTrace()");
            e.printStackTrace(System.out);
        }

        try {
            h();
        } catch (Exception e) {
            System.out.println("main:printStackTrace()");
            e.printStackTrace(System.out);
        }
    }
}
